package Servlet;

import com.mysql.jdbc.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Brian
 */
@WebServlet(name = "registration", urlPatterns = {"/submitinfo.html"})
public class registration extends HttpServlet {

    private boolean duplicateID = false;
    private boolean duplicateSSN = false;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        try {
            try {
                processRequest(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        try {
            try {
                processRequest(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException
        {
                JavaBeans.User user = new JavaBeans.User();
        String buttontype = (String) request.getParameter("cancel");
        if (buttontype != null && buttontype.equals("Cancel")) {
            response.sendRedirect("index.jsp");
            return;
        }
        
        if(!(request.getParameter("id")!=null&&request.getParameter("password")!=null&&
             request.getParameter("confirmpassword")!=null&&request.getParameter("email")!=null&&
                request.getParameter("address")!=null&&request.getParameter("lastname")!=null&&
                request.getParameter("firstname")!=null&&request.getParameter("zipcode")!=null&&
                request.getParameter("ssn")!=null&&request.getParameter("phone1")!=null&&
                request.getParameter("phone2")!=null&&request.getParameter("phone3")!=null&&
                request.getParameter("credit1")!=null&&request.getParameter("credit2")!=null&&
                request.getParameter("credit3")!=null&&request.getParameter("credit4")!=null))
            response.sendRedirect("index.jsp#divModalDialog5");
       
        try{
        request.setAttribute("duplicateid","");
        request.setAttribute("duplicateEmail","");
    
        user.setId(request.getParameter("id"));
        user.setPassword(request.getParameter("password"));
        user.setConfirmpassword(request.getParameter("confirmpassword"));
        user.setEmail(request.getParameter("email"));
        user.setAddress(request.getParameter("address"));
        user.setLastname(request.getParameter("lastname"));
        user.setFirstname(request.getParameter("firstname"));
        user.setZipcode(Integer.parseInt(request.getParameter("zipcode")));
        user.setSsn(Integer.parseInt(request.getParameter("ssn")));
        String phone = request.getParameter("phone1") + "-";
        phone += request.getParameter("phone2") + "-";
        phone += request.getParameter("phone3");
        String credit = request.getParameter("credit1") + "-";
        credit += request.getParameter("credit2") + "-";
        credit += request.getParameter("credit3") + "-";
        credit += request.getParameter("credit4");
        
        user.setCredit(credit);
        user.setPhone(phone);
        user.setRole('c');
        }
        catch(Exception e)
        {
            response.sendRedirect("index.jsp#divModalDialog5");
            return;
        }


        if (!user.getPassword().equals(user.getConfirmpassword()))
                    request.setAttribute("mismatchedPassword", "Invalid Password");
        
        if (addUserToDatabase(user, request)) {

            HttpSession session = request.getSession(true);
            session.setAttribute("user", user);
            response.sendRedirect("index.jsp");
        } else {
             if(duplicateID)
                request.setAttribute("duplicateID", "Error! The ID has already been registered!");
             if(duplicateSSN)
                request.setAttribute("duplicateSSN", "Error! The SSN has already been registered!");

            response.sendRedirect("index.jsp#divModalDialog5");
        }


    }
    /*
     * This class return true if new user is created. If there is a duplicate user
     * id, it will return false.
     *
     */

    public boolean addUserToDatabase(JavaBeans.User user,HttpServletRequest request) throws SQLException {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try{
            con = dataBaseController.getConnection();
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
            }
            
                st = con.createStatement();
                st = (Statement) con.createStatement();
                
                   
                st.executeUpdate("INSERT INTO `brchung`.`person` (`SSN`, `LastName`, `FirstName`, `Address`, `ZipCode`, `Telephone`, `password`, `role`, `id`) VALUES ("
                        + user.getSsn() + ", '"
                        + user.getLastname() + "', '"
                        + user.getFirstname() + "', '"
                        + user.getAddress() + "', "
                        + user.getZipcode() + ", '"
                        + user.getPhone() + "', '"
                        + user.getPassword() + "', 'c', '"
                        + user.getId() + "');");
                st.executeUpdate("INSERT INTO `brchung`.`client` (`Email`, `Rating`, `CreditCardNumber`, `Id`) VALUES ("
                        + "'"+ user.getEmail() + "', 1, '" + user.getCredit()+"', "+ user.getSsn() +");");
                st.executeUpdate("INSERT INTO `brchung`.`account` (`DateOpened`, `Client`) VALUES ("
                        +"CURDATE()"+",'"+user.getSsn()+"');");
                //st.close();
                //con.close();
                return true;
                
            } 
            catch (SQLException s)
            {
                request.setAttribute("duplicateSSN", s.getErrorCode());
                //con.close();
            }

        return false;


    }

    


}